<script setup lang="ts">
import type { FieldValues, PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'
import { useHotWordDelete, useHotWordIndex, useHotWordEnable, useHotWordMove } from '@fl/api/advertising-api/page-config'
import addOrEditHot from './hot-word-addOrEdit.vue'

const tableRef = ref()

const props = defineProps<{
    activeTreeId?: number | string,
}>()
const { activeTreeId } = toRefs(props)

const visible = ref<boolean>(false)
const editId = ref<string>('')

// 搜索条件、分页参数
const initialState = {
    hotWord: '',
}
const state = ref<FieldValues>(cloneDeep(initialState))
const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const initialPage = toRaw({ ...tablePage.value })

// 查询列表
const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    pageResourceId: activeTreeId.value,
    ...state.value
}))
const { data, isLoading } = useHotWordIndex(params)
const records = ref()
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.rows)
        tablePage.value.total = data.value.total!
    }
})

// 删除
const { mutate: deleteMutate } = useHotWordDelete()

// 搜索
function submit(values: FieldValues) {
    state.value = { ...values }
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    state.value = initialState
    tablePage.value = initialPage
}

// 新增
function goToAdd() {
    visible.value = true
}

// 编辑
function goToEdit(row: any) {
    editId.value = row.id
    visible.value = true
}

// 删除
function deleteConfirm(row: any) {
    ElMessageBox.confirm(
        `您确认要删除该热词吗`,
        '删除',
        {
            cancelButtonText: '取消',
            confirmButtonText: '删除',
            type: 'warning',
        },
    )
        .then(() => {
            const params = {
                id: row.id,
            }
            deleteMutate(params, {
                onSuccess: () => {
                    ElMessage.success('操作成功')
                }
            })
        }).catch(() => {

        })

}

// 启用禁用
const { mutate: enableMutate } = useHotWordEnable()
function switchActiveStatus(row) {
    console.log('switchActiveStatus', row)
    const params = {
        id: row.id,
        enable: row.activeStatus,
    }
    enableMutate(params, {
        onSuccess: () => {
            const tips = row.activeStatus === 1 ? '已启用' : '已禁用'
            ElMessage({
                message: tips,
                type: row.activeStatus === 1 ? 'success' : 'info',
            })
        }
    })

}

// 移动
const { mutate: moveMutate } = useHotWordMove()
function moveItem(row, type) {
    // 1置顶 2上移 3下移 4置底
    const params = {
        id: row.id,
        move: type,
    }
    moveMutate(params, {
        onSuccess: () => {
            ElMessage({
                type: 'success',
                message: '操作成功',
            })
        }
    })
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const columns: PlusColumn[] = [
    {
        label: '热词',
        prop: 'hotWord',
        valueType: 'copy'
    }
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'hotWord', title: '热词' },
        { field: 'sort', title: '排序' },
        { field: 'creator', title: '创建人' },
        { field: 'createTime', title: '创建时间' },
        { field: 'remark', title: '备注' },
        { field: 'activeStatus', slots: { default: 'activeStatus' }, title: '启用/禁用' },
        { slots: { default: 'operate' }, title: '操作', width: 300 }
    ]
})
</script>

<template>
    <ElCard class="top" shadow="never">
        <SearchForm v-bind="state" :columns="columns" submit-text="搜索" @reset="reset" @submit="submit" />
    </ElCard>

    <ElCard shadow="never">
        <SearchTable ref="tableRef" v-bind="gridOptions" v-model:pager="tablePage" :loading="isLoading" :data="records"
            @page-change="handlePageChange">
            <template #areaName="{ row }">
                {{ row.areaName }}
            </template>

            <template #toolbar_buttons>
                <ElButton type="primary" @click="goToAdd">
                    <div class="i-ic:baseline-add size-16" />
                    新增
                </ElButton>
            </template>

            <template #activeStatus="{ row }">
                <el-switch v-model="row.activeStatus" :active-value="1" :inactive-value="0"
                    @change="switchActiveStatus(row)" />
            </template>

            <template #operate="{ row }">
                <el-button class="small" type="info" text :disabled="row.sort === 1" @click="moveItem(row, '2')"> 上移
                </el-button>

                <el-button class="small" type="info" text :disabled="row.sort === tablePage.total"
                    @click="moveItem(row, '3')"> 下移
                </el-button>

                <el-button class="small" type="info" text :disabled="row.sort === 1" @click="moveItem(row, '1')"> 置顶
                </el-button>

                <el-button class="small" type="info" text :disabled="row.sort === tablePage.total"
                    @click="moveItem(row, '4')"> 置底
                </el-button>

                <el-button class="small" type="primary" text @click="goToEdit(row)"> 编辑 </el-button>

                <el-button class="small" text type="warning" @click="deleteConfirm(row)"> 删除 </el-button>
            </template>
        </SearchTable>
    </ElCard>

    <addOrEditHot ref="addOrEditRef" v-model:visible="visible" v-model:id="editId" :activeTreeId="activeTreeId" />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
